import axios from 'axios'
import { useUserInfoStore } from '@/stores'

import $router from '@/router'
import { Msg } from '@/utils/tools'

const { VITE_ORDER_APP_BASE_API, VITE_APP_BASE_API } = import.meta.env

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL基地址部分
  baseURL: VITE_APP_BASE_API + VITE_ORDER_APP_BASE_API,
  // 超时
  timeout: 10000,
  withCredentials: false,
})

// request拦截器
service.interceptors.request.use(
  (config) => {
    // console.log(config)
    const userInfoStore = useUserInfoStore()
    const token = userInfoStore?.token
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    console.log(error)
    Promise.reject(error)
  },
)

// 添加响应拦截器
service.interceptors.response.use(
  (res) => {
    const userInfoStore = useUserInfoStore()

    // console.log(res)
    const code = res.data.code || 200
    if (code === 200) {
      return Promise.resolve(res.data)
    } else if (code === 401 || code === 403) {
      Msg('登录过期')
      // 清除token
      userInfoStore.deleteUserInfo()
      userInfoStore.deleteToken()
      // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
      setTimeout(() => {
        $router.push('/login')
      }, 500)
      return Promise.reject(res.data)
    } else if (code !== 200) {
      Msg(res.data.msg || '请求错误')
      return Promise.reject(res.data)
    } else {
      Msg('服务器繁忙')
      return Promise.reject(res.data)
    }
  },
  (error) => {
    // console.log(error)
    let { message } = error
    if (message == 'Network Error') {
      message = '接口连接异常'
    } else if (message.includes('timeout')) {
      message = '接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '接口' + message.substr(message.length - 3) + '异常'
    }
    message && Msg(message)
    return Promise.reject(error.response)
  },
)

export default service
